package com.zhangshitong.common;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.zhangshitong.util.JsonMapper;

@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {

	private static final String START_TIME ="requestStartTime";
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// 请求之后的处理,不管请求成功与否
		String url = request.getRequestURI().toString();
		long start = (long) request.getAttribute(START_TIME);
		long end = System.currentTimeMillis();
		log.info("request completed. url:{}, cost:{}", url, end - start);
		removeThreadLocalInfo();
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// 请求之后的处理(前提是这个请求得成功)
//      String url = request.getRequestURI().toString();
//      long start = (Long) request.getAttribute(START_TIME);
//      long end = System.currentTimeMillis();
//      log.info("request finished. url:{}, cost:{}", url, end - start);
		removeThreadLocalInfo();
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 请求之前的处理
		String url = request.getRequestURI().toString();
		Map parameterMap = request.getParameterMap();
		log.info("request start, url:{},params:{}",url,JsonMapper.obj2String(parameterMap));//正常不应该把请求参数直接输出到日志，需要对敏感信息做一些过滤
		long start = System.currentTimeMillis();
		request.setAttribute(START_TIME, start);
		return true;
	}
	
	public void removeThreadLocalInfo(){
		RequestHolder.remove();
	}

	
}
